﻿using System;

namespace Anycmd.Host
{
    using Anycmd.AC;
    using Exceptions;
    using Model;
    using Util;

    public sealed class PrivilegeBigramState : StateObject<PrivilegeBigramState>, IStateObject
    {
        private PrivilegeBigramState() { }

        public static PrivilegeBigramState Create(PrivilegeBigramBase privilegeBigram)
        {
            if (privilegeBigram == null)
            {
                throw new ArgumentNullException("privilegeBigram");
            }
            if (string.IsNullOrEmpty(privilegeBigram.SubjectType))
            {
                throw new CoreException("必须指定主授权授权类型");
            }
            if (string.IsNullOrEmpty(privilegeBigram.ObjectType))
            {
                throw new CoreException("必须指定授权授权类型");
            }
            ACSubjectType subjectType;
            ACObjectType acObjectType;
            if (!privilegeBigram.SubjectType.TryParse(out subjectType))
            {
                throw new CoreException("非法的主授权类型" + privilegeBigram.SubjectType);
            }
            if (!privilegeBigram.ObjectType.TryParse(out acObjectType))
            {
                throw new CoreException("非法的从授权类型" + privilegeBigram.ObjectType);
            }
            return new PrivilegeBigramState
            {
                Id = privilegeBigram.Id,
                SubjectType = subjectType,
                SubjectInstanceID = privilegeBigram.SubjectInstanceID,
                ObjectType = acObjectType,
                ObjectInstanceID = privilegeBigram.ObjectInstanceID,
                PrivilegeConstraint = privilegeBigram.PrivilegeConstraint,
                CreateOn = privilegeBigram.CreateOn,
                CreateBy = privilegeBigram.CreateBy,
                CreateUserID = privilegeBigram.CreateUserID,
                PrivilegeOrientation = privilegeBigram.PrivilegeOrientation
            };
        }

        public ACSubjectType SubjectType { get; private set; }

        public Guid SubjectInstanceID { get; private set; }

        public ACObjectType ObjectType { get; private set; }

        public Guid ObjectInstanceID { get; private set; }

        public string PrivilegeConstraint { get; private set; }

        public int PrivilegeOrientation { get; private set; }

        public DateTime? CreateOn { get; private set; }

        public string CreateBy { get; private set; }

        public Guid? CreateUserID { get; private set; }

        protected override bool DoEquals(PrivilegeBigramState other)
        {
            return Id == other.Id &&
                SubjectType == other.SubjectType &&
                SubjectInstanceID == other.SubjectInstanceID &&
                ObjectType == other.ObjectType &&
                ObjectInstanceID == other.ObjectInstanceID &&
                PrivilegeConstraint == other.PrivilegeConstraint &&
                PrivilegeOrientation == other.PrivilegeOrientation;
        }
    }
}
